In this tutorial, we will discuss some loop conditions and techniques to control the loop flow and its execution. We will also discuss how can we use the break and continue statements inside a loop. In python, we have two loop statements
for
and
while
.
We use
for
loop
when we have a certain number, how many times we want to loop over a statement. And use while loop when we do not have a number, and iterate over a statement until a certain condition becomes false.
Infinity Loop
In programming, a developer always tries to avoid infinity loop, so whenever a programmer writes a loop statement, he always takes extra care about that statement. In Infinity loop the block of code inside the loop executes for infinite times and it can crash your program. In Python, the infinite loop problem can arise with
while
loop because it works on conditions (True or False), so if the condition never becomes false the while loop will goanna execute for infinite times.
Example:
while True:
print("This statement will print infinite times")
Loop with the condition at the top
while
loop works with boolean values or conditions, and we write the condition along with the statement. In
while
loop, the condition is written at the top with the while statement itself, and it determines the iteration of the while block. The while statement iterates again and again until the condition become
False
.
Example:
n = int(input("Enter the number "))
mul = 1
i = 1
while i <= n:
mul = mul * i
i = i+1
print("The multiplication of n numbers is",mul)
Output:
Enter the number 4
The multiplication of n numbers is 24
Loop with Condition in the middle
With the help of
break
statement, we can terminate the iteration of loop, so when we say the condition in the middle of the loop, we mean we put an
if
condition inside a
while
loop which contains the
break
statement, that can terminate the loop.
Example:
while True:
a = input("Enter an Alphabet: ")
if a.isapha():
break
print("Try Again!")
print("You entered",a)
Output:
Enter an Alphabet: 11b
Enter an Alphabet: 9
Enter an Alphabet: C
You entered C
Loop with Conditions at the bottom
When the condition is at bottom no matter what the boolean value that condition takes the loop will execute at least one time. In other programming languages, we have a concept of do while in which the condition stays at the last of the while statement.
Example:
while True:
name= input("Enter your name: ")
age = input("Enter your age: ")
choice =input("Do you want to edit your Name and age y/n (yes/no): ")
if choice.lower()[0] == 'n':
break
print("Wellcome", name)
Output:
Enter your name: Sam
Enter your age: 29
Do you want to edit your Name and age y/n (yes/no): y
Enter your name: Sam Smith
Enter your age: 29
Do you want to edit your Name and age y/n (yes/no): n
Wellcome Sam Smith